package com.anxin.controller;

import org.springframework.security.core.GrantedAuthority;
import com.anxin.common.Result;
import com.anxin.entity.SysUser;
import com.anxin.service.SysUserService;
import com.anxin.security.jwt.JwtTokenProvider;
import com.anxin.system.dto.LoginDTO;
import com.anxin.system.dto.RegisterDTO;
import com.anxin.system.dto.UserInfoDTO;
import com.anxin.util.RedisUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "认证管理", description = "认证相关接口")
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider tokenProvider;

    private final SysUserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<String> login(@RequestBody LoginDTO loginDTO) {
        try {
            // 使用Spring Security的AuthenticationManager进行身份验证
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword()));

            // 将认证信息存入安全上下文
            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 使用JwtTokenProvider生成JWT令牌
            String jwt = tokenProvider.generateToken(loginDTO.getUsername());

            // 构造Redis Key
            String redisKey = "user:auth:" + jwt;

            // 假设UserDetails是用户信息的具体类型，这里可以存储更多用户相关信息
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();

            // 构造 UserInfoDTO
            UserInfoDTO userInfo = new UserInfoDTO();
            userInfo.setUsername(userDetails.getUsername());
            userInfo.setAuthorities(userDetails.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .toList());

            // 假设 SysUserServiceImpl 或其他服务中可获取角色 ID
            SysUser sysUser = userService.findByUsername(loginDTO.getUsername());
            if (sysUser != null) {
                // 将角色 ID 添加到 UserInfoDTO 中
                userInfo.setUserId(sysUser.getId());
                userInfo.setRoleId(sysUser.getRoleId());
            }

            // 写入Redis，设置过期时间（例如30分钟）
            RedisUtil.set(redisKey, userInfo, 30 * 60); // 设置30分钟过期

            // 返回成功结果，包含生成的JWT令牌
            return Result.success(jwt);
        } catch (Exception e) {
            // 捕获异常并返回错误信息
            return Result.error("用户名或密码错误");
        }
    }


    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@Valid @RequestBody RegisterDTO registerDTO) {
        userService.register(registerDTO);
        return Result.success();
    }

    @PostMapping("/logout")
    public Result<Void> logout() {
        SecurityContextHolder.clearContext();
        return Result.success();
    }
}
